package cc.fs.study.hotfix;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.alipay.euler.andfix.patch.PatchManager;
import java.io.IOException;

/**
 * 热修复
 * 问题:
 * 1.怎么知道是否有新的补丁
 * 2.新的补丁下载后需要记录,避免重新下载或者下载失败
 */
public class HotFix {
    private PatchManager patchManager;

    public HotFix(Context context){
        patchManager = new PatchManager(context);
        //当前版本号
        patchManager.init(getVision(context));
        //加载已经在patchManager中的patch
        patchManager.loadPatch();
    }

    private String getVision(Context context){
        try {
            PackageInfo info;
            PackageManager packageManager = context.getPackageManager();
            info = packageManager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0";
        }
    }

    /**
     * 下载完成后将新的path加入到patchManager中
     */
    public void addPatch(String path) throws IOException {
        patchManager.addPatch(path);
    }

    /**
     * 更新应用,清除曾经depath
     */
    public void cleanPatch(){
        patchManager.removeAllPatch();
    }

}
